﻿using System;
using System.Data;
using System.Text;
using System.Web.UI;
using System.Web.UI.WebControls;
using WeiXinPF.Common;
using WeiXinPF.Modules.CDRT.SmartCity.Application.DTO;
using WeiXinPF.Modules.CDRT.SmartCity.Application.Services;
using WeiXinPF.Web.UI;

namespace WeiXinPF.Web.modules.cdrt.smart
{
    /// <summary>
    /// 消息管理
    /// 用于管理员查看用户提交的爆料及留言
    /// </summary>
    public partial class message_manager : ManageListPage
    {
        #region Peoperties

        /// <summary>
        /// 消息类别
        /// </summary>
        public int CategoryId { get; private set; }

        /// <summary>
        /// 查询关键字
        /// </summary>
        public string KeyWord { get; private set; }

        #endregion

        protected void Page_Load(object sender, EventArgs e)
        {
            this.CategoryId = MXRequest.GetQueryInt("category_id");
            this.KeyWord = MXRequest.GetQueryString("keywords");

            this.PageSize = GetPageSize(10);

            if (!Page.IsPostBack)
            {
                //BindDropDownList();
                BindRepeatList(this.CategoryId, this.KeyWord, "extInt asc,createdate desc ");
            }
        }

        #region Binding Event Handlers

        /// <summary>
        /// 绑定类别下拉框
        /// </summary>
        private void BindDropDownList()
        {
            Model.wx_userweixin weixin = GetWeiXinCode();
            var wid = weixin.id;

            BLL.wx_product_type bll = new BLL.wx_product_type();
            DataTable dt = bll.GetWCodeList(weixin.id, 0);

            this.ddlCategoryId.Items.Clear();
            this.ddlCategoryId.Items.Add(new ListItem("所有类别", ""));
            foreach (DataRow dr in dt.Rows)
            {
                string Id = dr["id"].ToString();
                int ClassLayer = int.Parse(dr["class_layer"].ToString());
                string Title = dr["tName"].ToString().Trim();

                if (ClassLayer == 1)
                {
                    this.ddlCategoryId.Items.Add(new ListItem(Title, Id));
                }
                else
                {
                    Title = "├ " + Title;
                    Title = Utils.StringOfChar(ClassLayer - 1, "　") + Title;
                    this.ddlCategoryId.Items.Add(new ListItem(Title, Id));
                }
            }
        }

        /// <summary>
        /// 绑定列表
        /// </summary>
        /// <param name="categoryId"></param>
        /// <param name="strWhere"></param>
        /// <param name="orderby"></param>
        private void BindRepeatList(int categoryId, string keyWord, string orderby)
        {
            Model.wx_userweixin weixin = GetWeiXinCode();
            var wid = weixin.id;
            if (this.CategoryId > 0)
            {
                this.ddlCategoryId.SelectedValue = categoryId.ToString();
            }
            string gettype = this.ddlCategoryId.SelectedItem.Text;
            this.txtKeywords.Text = this.KeyWord;

            IMessageService service = new MessageService();
            var messages = service.GetAllMessages(wid, keyWord, gettype);
            foreach (MessageDTO mg in messages)
            {
                //if (mg.status == 0) { mg.status_ = "未审核"; }
                //if (mg.status == 1) { mg.status_ = "通过审核"; }
                //if (mg.status == 2) { mg.status_ = "未通过审核"; }
            }

            /*
            var strWhere = string.Format(" id > 0 and hdName like '%" + keyWord + "%'"); ;
            BLL.wx_product bll = new BLL.wx_product();
            DataSet artDs = bll.GetWCodeList(weixin.id, categoryId,
                this.PageSize, this.PageIndex, strWhere, orderby, out this.TotalCount);

            if (artDs != null)
            {
                DataRow dr;
                for (int i = 0; i < artDs.Tables[0].Rows.Count; i++)
                {
                    dr = artDs.Tables[0].Rows[i];
                    dr["url"] = " <a href=\"javascript:;\">" + MyCommFun.getWebSite() + "/modules/cdrt/smart/message.aspx?wid=" + MyCommFun.ObjToStr(dr["wid"]) + "&id=" + dr["id"] + "</a>";
                }
            }

            this.rptList.DataSource = artDs;
            this.rptList.DataBind();
            */

            this.rptList.DataSource = messages;
            this.rptList.DataBind();

            txtPageNum.Text = this.PageSize.ToString();
            string pageUrl = Utils.CombUrlTxt("message_manager.aspx", "category_id={0}&keywords={1}&page={2}", ddlCategoryId.SelectedValue, this.KeyWord, "__id__");
            PageContent.InnerHtml = Utils.OutPageList(this.PageSize, this.PageIndex, this.TotalCount, pageUrl, 8);
        }

        /// <summary>
        /// 刷新页面数据
        /// </summary>
        private void Refresh()
        {
            string keyWord = txtKeywords.Text;
            string categoryId = ddlCategoryId.SelectedValue;
            Response.Redirect(Utils.CombUrlTxt("message_manager.aspx",
                "category_id={0}&keywords={1}", categoryId, keyWord));
        }

        #endregion

        #region Button Event Handlers

        /// <summary>
        /// 查询按钮操作
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void OnButtonSearchClick(object sender, EventArgs e)
        {
            Refresh();
        }

        /// <summary>
        /// 删除按钮操作
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void OnButtonDeleteClick(object sender, EventArgs e)
        {
            ChkAdminLevel("message_manager", MXEnums.ActionEnum.Delete.ToString());
           // rptList = this.rptList;
            for (int i = 0; i < rptList.Items.Count; i++)
            {
                int id = Convert.ToInt32(((HiddenField)rptList.Items[i].FindControl("hidId")).Value);
                CheckBox cb = (CheckBox)rptList.Items[i].FindControl("chkId");
                if (cb.Checked)
                {
                    new WeiXinPF.Modules.CDRT.SmartCity.Application.Services.MessageService().DeleteMessage(id);
                }
            }
            AddAdminLog(MXEnums.ActionEnum.Edit.ToString(),
                "删除完毕！");
            Refresh();
        }

        #endregion

        #region DropDownList Event Handlers

        /// <summary>
        /// 下拉框切换时刷新数据
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void OnDropDownListCategorySelectedIndexChanged(object sender, EventArgs e)
        {
            Refresh();
        }

        #endregion

        /// <summary>
        /// 分页改变时刷新数据
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void OnTextBoxPageNumberTextChanged(object sender, EventArgs e)
        {
            int pagesize;
            if (int.TryParse(txtPageNum.Text.Trim(), out pagesize))
            {
                if (pagesize > 0)
                {
                    Utils.WriteCookie("message_list_page_size", pagesize.ToString(), 43200);
                }
            }
            Refresh();
        }

        protected void rptList_ItemDataBound(object sender, RepeaterItemEventArgs e)
        {
            if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
            {
                var message = (MessageDTO)e.Item.DataItem;
                if (string.IsNullOrEmpty(message.file_path))
                {
                    return;
                }

                string filePath = message.file_path;
                //filePath = filePath.Replace('<', ' ').Replace('>', ' ').Trim();
                var files = filePath.Split(new char[] { '<',',' },StringSplitOptions.RemoveEmptyEntries);
                if (files.Length == 0)
                {
                    return;
                }

                StringBuilder htmlBuilder = new StringBuilder();

                for (int i = 0; i < files.Length; i++)
                {
                    var fileName = files[i];
                    if (fileName.EndsWith(".jpg"))
                    {
                        var src = fileName;
                        htmlBuilder.AppendFormat("<div class=\"gallery\"><a href=\"{0}\"><img style=\"max-width:25px;max-height:25px;\" src=\"{0}\" alt=\"\" title=\"{1}\" /></a></div>", src, message.content);
                    }
                    else if (fileName.EndsWith(".mov") || fileName.EndsWith(".mp4"))
                    {
                        var src = fileName;
                        htmlBuilder.AppendFormat("<a href=\"{0}\"><img style=\"width:25px;height:25px;\" src=\"../../../modules/cdrt/smart/images/video.jpg\" alt=\"\" title=\"{1}\" /></a>", src, message.content);
                        //htmlBuilder.AppendFormat("<a href=\"{0}\" data-poptrox=\"youtube, 800x480\"><img src=\"/modules/cdrt/smart/images/video.jpg\" alt=\"\" title=\"{1}\" /></a><video controls=\"controls\" style=\"width: 100% \" src=\"{0}\"></video>", src, message.content);
                        /*
                        htmlBuilder.AppendFormat("<video controls=\"controls\" style=\"width: 100% \" src=\"{0}\"></video>", fileName);
                        */
                        //htmlBuilder.AppendFormat("<a class=\"media\" href=\"{0}\">{1}</a>",src,message.content);
                    }
                }

                ((Label)e.Item.FindControl("RatingLabel")).Text = htmlBuilder.ToString();
            }
        }

        protected void btnPassClick(object sender, EventArgs e)
        {
            string resumeId = (((LinkButton)sender).CommandArgument.ToString());
            MessageDTO msg = new WeiXinPF.Modules.CDRT.SmartCity.Application.Services.MessageService().GetMessage(int.Parse(resumeId));
            WeiXinPF.Modules.CDRT.SmartCity.Domain.Models.Message m = new Modules.CDRT.SmartCity.Domain.Models.Message();
            m.content = msg.content;
            m.create_time = msg.create_time;
            m.file_path = msg.file_path;
            m.idcard = msg.idcard;
            m.message_id = msg.message_id;
            m.mobile = msg.mobile;
            m.openid = msg.openid;
            m.status = 1;
            m.title = msg.title;
            m.type_ = msg.type_;
            m.user_id = msg.user_id;
            m.user_name = msg.user_name;
            m.wid = msg.wid;
            m.update_time = DateTime.Now;
            new WeiXinPF.Modules.CDRT.SmartCity.Application.Services.MessageService().UpdateMessage(m);
            
            Refresh();
        }



        protected void btnUnPassClick(object sender, EventArgs e)
        {
            string resumeId = (((LinkButton)sender).CommandArgument.ToString());
            MessageDTO msg = new WeiXinPF.Modules.CDRT.SmartCity.Application.Services.MessageService().GetMessage(int.Parse(resumeId));
            WeiXinPF.Modules.CDRT.SmartCity.Domain.Models.Message m = new Modules.CDRT.SmartCity.Domain.Models.Message();
            m.content = msg.content;
            m.create_time = msg.create_time;
            m.file_path = msg.file_path;
            m.idcard = msg.idcard;
            m.message_id = msg.message_id;
            m.mobile = msg.mobile;
            m.openid = msg.openid;
            m.status = 2;
            m.title = msg.title;
            m.type_ = msg.type_;
            m.user_id = msg.user_id;
            m.user_name = msg.user_name;
            m.wid = msg.wid;
            m.update_time = DateTime.Now;
            new WeiXinPF.Modules.CDRT.SmartCity.Application.Services.MessageService().UpdateMessage(m);
            Refresh();
        }




        public string getstatus(string status)
        {
            if (status == "0")
                return "未审核";
            else if (status == "1")
                return "已审核";
            else if (status == "2")
                return "审核失败";
            return "未定义状态";
        }

        public string getdisplay(string status)
        {
            if (status == "0")
                return "inline";
            else 
                return "none";
        }
    }
}